package com.autocloud.service;

import com.autocloud.model.security.Account;
import com.autocloud.model.security.Person;
import com.autocloud.repository.AccountRepository;
import com.autocloud.repository.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author zhongwb
 * @version 1.0
 * @description
 * @date 2019/12/28 12:03 下午
 */
@Service
public class AccountService {

    @Autowired
    AccountRepository accountRepository;

    @Autowired
    PersonRepository personRepository;

    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    public boolean updateUserInfo(Map<String, String> param, String accountId) {
        Optional<Person> personResult = accountRepository.findByAccountId(accountId);
        if(!personResult.isPresent()){
            return false;
        }
        Person person = personResult.get();
        person.setTitle(param.get("title"));
        person.setAddress(param.get("address"));
        person.setAvatar(param.get("avatar"));
        person.setEmail(param.get("email"));
        person.setPhone(param.get("phone"));
        person.setGender(param.get("gender"));
        personRepository.save(person);
        return true;
    }


    public boolean isEqualPassword(String accountId,String oldPassword){
        //匹配原密码，是否对应
        List<String> ids = new ArrayList<>();
        ids.add(accountId);
        List<Account> account = accountRepository.findAllByIdIn(ids);
        if(account.size() == 0){
            return false;
        }
        if(!bCryptPasswordEncoder.encode(oldPassword.toLowerCase()).equals(account.get(0).getPwd())){
            return false;
        }
        return true;
    }

    public boolean newPassword(Map<String, String> param, String accountId) {
        //匹配原密码，是否对应
        List<String> ids = new ArrayList<>();
        ids.add(accountId);
        List<Account> accountList = accountRepository.findAllByIdIn(ids);
        if(accountList.size() == 0){
            return false;
        }
        String oldPassword = param.get("oldPassword");
        String newPassword = param.get("newPassword");
        Account account = accountList.get(0);

        if (!bCryptPasswordEncoder.matches(oldPassword, account.getPwd())) {
            return false;
        }

        account.setPwd(bCryptPasswordEncoder.encode(newPassword.toLowerCase()));
        accountRepository.save(account);
        return true;
    }

}
